package com.gx.util.base;

import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author gaoxing
 * @create 2018-06-19 下午3:36
 */
public class BaseZipUtils {
    public static String zip(String content) {
        return StringUtils.isBlank(content) ? content : new String(zip(content.getBytes(Charsets.UTF_8)), Charsets.ISO_8859_1);
    }

    public static String unzip(String content) {
        return StringUtils.isBlank(content) ? content : new String(unzip(content.getBytes(Charsets.ISO_8859_1)), Charsets.UTF_8);
    }

    public static byte[] zip(byte[] content) {
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(1024);
        try (GZIPOutputStream output = new GZIPOutputStream(byteOutput)) {
            output.write(content);
        } catch (Throwable e) {
            throw new RuntimeException("gzip压缩异常", e);
        }
        return byteOutput.toByteArray();
    }

    public static byte[] unzip(byte[] content) {
        try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(content))) {
            return IOUtils.toByteArray(in);
        } catch (Throwable e) {
            throw new RuntimeException("unzip解压缩异常", e);
        }
    }

}
